﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Services.SMARTMobileServiceReference;
using SMARTMobile.WinPhone;

namespace SMARTMobile.ViewModels
{
    public class DongBoPageViewModel : ViewModelBase
    {
        private SmartMobileDBContext _smartMobileContext;
        private ReloadDataSmartPhoneSoapClient _proxy;
        List<TCARCUST> updateTcarcusts = new List<TCARCUST>();
        private int countUpdate = 0;
        private int countUpdateComplete = 0;
        private bool _isCheckedInformation;
        public DongBoPageViewModel()
        {
            this.ThoatCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteThoatCommand
            };

            this.SaveCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteSaveCommand
            };

            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
            this._proxy.InsertCustomerkeyCompleted += _proxy_InsertCustomerkeyCompleted;
            this._proxy.UploadCustomerImageCompleted += _proxy_UploadCustomerImageCompleted;

            if (GlobalInformation.ReportImageTypes == null || !GlobalInformation.ReportImageTypes.Any())
            {
                GlobalInformation.ReportImageTypes = GetImageType();
            }
        }

        public ICommandRoute ThoatCommand { get; private set; }

        public ICommandRoute SaveCommand { get; private set; }

        public bool IsCheckedInformation
        {
            get { return _isCheckedInformation; }
            set
            {
                _isCheckedInformation = value;
                base.RaisePropertyChanged("IsCheckedInformation");
            }
        }


        private void ExecuteSaveCommand(object commandParams)
        {
            this.IsBusy = true;
            this.SaveCommand.RaiseCanExecuteChanged(true);
            countUpdate = 0;
            updateTcarcusts.Clear();
            if (this.IsCheckedInformation)
            {
                // Nhan Vien
                if (GlobalInformation.ArSaleSPType.Usertype != "SS")
                {
                    // Save PhoneVender
                    foreach (var phoneVendor in this._smartMobileContext.PhonevendorVolume)
                    {
                        this._proxy.UploadPhonevendorVolumeAsync(GlobalInformation.SiteCode,
                            phoneVendor.CustomerKey, phoneVendor.PhoneVendorCode,
                            (phoneVendor.WhosesaleVolume ?? 0).ToString(), (phoneVendor.RetailVolume ?? 0).ToString(),
                            (phoneVendor.WhosesaleValue ?? 0).ToString(), (phoneVendor.RetialValue ?? 0).ToString());
                    }

                    // Save PriceRange
                    foreach (var priceRange in this._smartMobileContext.PriceRangeContribution)
                    {
                        this._proxy.UploadPriceRangeContributionAsync(GlobalInformation.SiteCode,
                            priceRange.CustomerKey, priceRange.PriceRangeCode
                            , (priceRange.ContributionByValue ?? 0).ToString(),
                            (priceRange.ContributionByVolume).ToString());
                    }

                    // Save UploadOutletNokiaPG
                    foreach (var nokiaPG in this._smartMobileContext.OutletNokiaPG)
                    {
                        this._proxy.UploadOutletNokiaPGAsync(GlobalInformation.SiteCode,
                            nokiaPG.Customerkey, nokiaPG.PGCode, nokiaPG.StartWorkingTime.ToString(),
                            nokiaPG.EndWorkingTime.ToString());
                    }

                    // Save UploadOutletPGInformation
                    foreach (var pgInformation in this._smartMobileContext.OutetPGInformation)
                    {
                        this._proxy.UploadOutletPGInformationAsync(GlobalInformation.SiteCode,
                            pgInformation.Customerkey, pgInformation.PhoneVendorCode,
                            (pgInformation.Qty ?? 0).ToString());
                    }

                    // Save OutltVendorContribution
                    foreach (var outletVendorContribution in this._smartMobileContext.OutletVendorContribution)
                    {
                        this._proxy.UploadOutltVendorContributionAsync(GlobalInformation.SiteCode,
                            outletVendorContribution.CustomerKey, outletVendorContribution.OutletVendorKey,
                            (outletVendorContribution.ContributionAmt ?? 0).ToString());
                    }

                    // Save Contact Infor
                    foreach (var outletContact in this._smartMobileContext.OutletContact)
                    {
                        this._proxy.UploadContactInforAsync(GlobalInformation.SiteCode,
                            outletContact.CustomerKey, outletContact.Fullname,
                            outletContact.Role, (outletContact.Gender ?? true).ToString(), outletContact.Email,
                            outletContact.Phone, outletContact.Title);
                    }

                    // Save current out
                    foreach (var currentOut in this._smartMobileContext.CurrentOutDoorDisplay)
                    {
                        string image = string.Empty;
                        string imageName = "NhapDuLieu\\" + "OUT" + currentOut.Customerkey + currentOut.PhoneVendorCode +
                                           currentOut.OutDoorTypeCode + ".jpeg";
                        if (Utilities.ImageUtilities.CheckFileExist(imageName))
                        {
                            image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                        }

                        this._proxy.UploadCurrentOutDoorDisplayAsync(GlobalInformation.SiteCode,
                            currentOut.Customerkey, currentOut.PhoneVendorCode,
                            currentOut.OutDoorTypeCode, (currentOut.Qty ?? 0).ToString(), image);
                    }

                    // Save current in
                    foreach (var currentIn in this._smartMobileContext.CurrentInDoorDoorDisplay)
                    {
                        string image = string.Empty;
                        string imageName = "NhapDuLieu\\" + "IN" + currentIn.CustomerKey + currentIn.PhoneVendorCode +
                                           currentIn.InDoorTypeCode + ".jpeg";
                        if (Utilities.ImageUtilities.CheckFileExist(imageName))
                        {
                            image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                        }

                        this._proxy.UploadCurrentInDoorDoorDisplayAsync(GlobalInformation.SiteCode,
                            currentIn.CustomerKey, currentIn.PhoneVendorCode,
                            currentIn.InDoorTypeCode, currentIn.Qty, image);
                    }

                    // Save Merchandising
                    foreach (var merchandising in this._smartMobileContext.OutletNokiaMerchandisingPotential)
                    {
                        string image = string.Empty;
                        string imageName = "Merchandising\\" + merchandising.Customerkey + merchandising.MerchandisingCode + ".jpeg";
                        if (Utilities.ImageUtilities.CheckFileExist(imageName))
                        {
                            image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                        }

                        this._proxy.UploadOutletNokiaMerchandisingPotentialAsync(GlobalInformation.SiteCode,
                            merchandising.Customerkey, merchandising.MerchandisingCode, image, (merchandising.CaptureTiming ?? DateTime.Now).ToLongDateString());
                    }
                }

                foreach (var customer in this._smartMobileContext.TCARCUST)
                {
                    // Check mark of new customer
                    if (customer.Customerkey.Contains("_") || customer.IsEdit == "2")
                    {
                        updateTcarcusts.Add(customer);
                    }
                }

                if (updateTcarcusts != null && updateTcarcusts.Any())
                {
                    foreach (var customer in updateTcarcusts)
                    {
                        this._proxy.InsertCustomerkeyAsync(customer.Customerkey,
                            GlobalInformation.SiteCode,
                           customer.Customername,
                           customer.ShopOwner,
                           customer.Address,
                           customer.Street,
                           customer.Ward,
                           customer.Town ?? string.Empty,
                           customer.Provice ?? string.Empty,
                           customer.DeliveryAddress ?? string.Empty,
                           customer.Phone ?? string.Empty,
                           customer.TradeSegment ?? string.Empty,
                           customer.SubTradeSegment ?? string.Empty,
                           customer.SubTradeSegment ?? string.Empty,
                           customer.Otype ?? string.Empty,
                           customer.VLevel ?? string.Empty,
                           customer.StatusType ?? string.Empty,
                           customer.Salespkey ?? string.Empty,
                           customer.Lat ?? string.Empty,
                           customer.Long ?? string.Empty,
                           customer.Customerkey ?? string.Empty);
                    }
                }
                else
                {
                    this.IsBusy = false;
                    this.SaveCommand.RaiseCanExecuteChanged(true);
                }

                //this.IsBusy = false;
                //this.ShowMessage("Đồng bộ dữ liệu thành công");
            }
            else
            {
                this.IsBusy = false;
                this.SaveCommand.RaiseCanExecuteChanged(true);
            }
        }

        private void ExecuteThoatCommand(object commandParams)
        {
            this.ThoatCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("Main");
        }

        private List<IMAGETYPE> GetImageType()
        {
            try
            {
                // It will copy from local to iso
                _smartMobileContext.CreateIfNotExists();

                // log sql query native on Output window
                _smartMobileContext.LogDebug = true;

                // Query - Same with SQL SERVER Linq
                List<IMAGETYPE> list = new List<IMAGETYPE>();
                return _smartMobileContext.IMAGETYPE.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        void _proxy_InsertCustomerkeyCompleted(object sender, InsertCustomerkeyCompletedEventArgs e)
        {
            countUpdate++;
            // New Customer
            if (e.Result != "0")
            {
                if (!string.IsNullOrEmpty(e.UserState.ToString()))
                {
                    // Update customer key on local database
                    if (GlobalInformation.SelectedTCARCUS != null)
                    {
                        GlobalInformation.SelectedTCARCUS.Customerkey = e.Result;
                    }

                    // Update TCARCUST
                    var currentTCARCUST = (from tcr in _smartMobileContext.TCARCUST where tcr.Customerkey == e.Result select tcr).FirstOrDefault();
                    if (currentTCARCUST != null)
                    {
                        currentTCARCUST.Customerkey = e.Result;
                    }

                    var currentShopVisit = (from shop in _smartMobileContext.Shopvisit where shop.CustomerKey == e.Result select shop).FirstOrDefault();
                    if (currentShopVisit != null)
                    {
                        currentShopVisit.CustomerKey = e.Result;
                    }

                    var currentIMAGECUSTOMER = (from shop in _smartMobileContext.IMAGECUSTOMER where shop.CustomerKey == e.Result select shop).ToList();

                    foreach (var imagecustomer in currentIMAGECUSTOMER)
                    {
                        imagecustomer.CustomerKey = e.Result;
                    }

                    _smartMobileContext.SubmitChanges();
                }
            }

            if (countUpdate == updateTcarcusts.Count)
            {
                // Upload shop visit
                foreach (var shopVisit in this._smartMobileContext.Shopvisit.ToList())
                {
                    this._proxy.UploadShopvisitAsync(shopVisit.CustomerKey, shopVisit.Lat ?? string.Empty,
                        shopVisit.Long ?? string.Empty,
                        shopVisit.DateVisit ?? string.Empty, GlobalInformation.ArSaleSPType.Usercode ?? string.Empty,
                        shopVisit.StartTime ?? string.Empty,
                        shopVisit.EndTime ?? shopVisit.StartTime, GlobalInformation.SiteCode ?? string.Empty,
                        shopVisit.CMode ?? string.Empty);
                }

                // Giam Sat
                if (GlobalInformation.ArSaleSPType.Usertype == "SS")
                {
                    // TODO: Upload shop APPROVALCUSTOMERINFOR
                    string appro = string.Empty;
                    foreach (var approvalCus in this._smartMobileContext.APPROVALCUSTOMERINFOR.ToList())
                    {
                        appro += "@" + approvalCus.Customerkey + "#" + approvalCus.Type + "#" + approvalCus.Key + "#" +
                                 approvalCus.Values + "#" + approvalCus.Comment;
                    }

                    this._proxy.ApprovalCustomerInforAsync(GlobalInformation.SiteCode ?? string.Empty,
                        GlobalInformation.ArSaleSPType.Usercode ?? string.Empty, appro);
                }

                // Upload Image
                var imageCustomerList = this._smartMobileContext.IMAGECUSTOMER.ToList();
                if (imageCustomerList.Count > 0)
                {
                    foreach (var imageCustomer in imageCustomerList)
                    {
                        if (GlobalInformation.ReportImageTypes != null)
                        {

                            string imagePath = imageCustomer.CustomerKey + "~" + imageCustomer.Type + ".Jpeg";
                            if (Utilities.ImageUtilities.CheckFileExist(imagePath))
                            {
                                string image = Utilities.ImageUtilities.ConvertBitmapToString(imagePath);
                                string formatRecDate = String.Format("{0:M/d/yyyy HH:mm:ss}",
                                    DateTime.Parse(imageCustomer.Recdate));
                                this._proxy.UploadCustomerImageAsync(
                                    GlobalInformation.SiteCode,
                                    imageCustomer.Salespkey,
                                    imageCustomer.Type,
                                    imageCustomer.CustomerKey,
                                    image,
                                    formatRecDate);
                            }
                        }
                    }
                }
                else
                {
                    countUpdateComplete++;
                    if (countUpdateComplete == updateTcarcusts.Count)
                    {
                        this.IsBusy = false;
                        this.ShowMessage("Đồng bộ dữ liệu thành công");
                        this.ThoatCommand.RaiseCanExecuteChanged(true);
                    }
                }
            }
        }

        private void _proxy_UploadCustomerImageCompleted(object sender, UploadCustomerImageCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                countUpdateComplete++;
                if (countUpdateComplete == updateTcarcusts.Count)
                {
                    this.IsBusy = false;
                    this.ShowMessage("Đồng bộ dữ liệu thành công");
                    this.ThoatCommand.RaiseCanExecuteChanged(true);
                }
            }
        }

        protected void ShowMessage(string message)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(message));
        }

    }
}
